package com.zzzy.cont.controller.mycon;

import com.zhuozhengsoft.pageoffice.DocumentOpenType;
import com.zhuozhengsoft.pageoffice.FileMakerCtrl;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.word.DataTagWriter;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import com.zzzy.cont.common.util.AmountTransUtil;
import com.zzzy.cont.dao.entity.ConFileTemplate;
import com.zzzy.cont.service.ConFileTemplateService;
import com.zzzy.cont.service.mycon.MyConDraftService;
import com.zzzy.cont.vo.contract.my.ConAddReq;
import com.zzzy.cont.vo.contract.my.ConBasicInfoRes;
import com.zzzy.cont.vo.contract.my.ConFileTemplateForSelectPageReq;
import com.zzzy.cont.vo.contract.my.ConUpdateReq;
import com.zzzy.framework.common.annotation.RepeatSubmit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;

/**
 * 我的合同
 *
 * @author fc
 * @since 2024-05-27
 */
@Tag(name = "我的合同-起草中", description = "con108")
@Validated
@RestController
@RequestMapping("/con/my")
public class MyConDraftController {

    @Resource
    private MyConDraftService myConDraftService;
    @Resource
    private ConFileTemplateService conFileTemplateService;

    @RepeatSubmit
    @PostMapping("/add")
    @Operation(summary = "新增合同")
    @Parameter(name = "conFile", description = "上传的文件")
    @PreAuthorize("@pvs.hasPermission('con:my:add')")
    public AjaxResult<Long> add(MultipartFile conFile, @Valid @ParameterObject ConAddReq addReq) {
        return AjaxResult.success(myConDraftService.addCon(addReq));
    }

    @GetMapping("/createConNo")
    @Operation(summary = "获取合同编号")
    @PreAuthorize("@pvs.hasPermission('con:my:add')")
    public AjaxResult createConNo() {
        return AjaxResult.success(myConDraftService.createConNo());
    }

    @PostMapping("/wordAutoFill/{id}")
    @Operation(summary = "word自动填充")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void wordAutoFill(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id
            , HttpServletRequest request, HttpServletResponse response) throws IOException {
        ConBasicInfoRes conBasicInfo = myConDraftService.getConBasicInfo(id);

        String openFileUrl = "/con/my/getConFileStream/" + id;
        FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
        //数据标签
        WordDocumentWriter doc = new WordDocumentWriter();
        DataTagWriter tradeCompanyDt = doc.openDataTag("【交易公司名称】");
        tradeCompanyDt.setValue(conBasicInfo.getTradeCompany());
        DataTagWriter contactNoDt = doc.openDataTag("【合同编号】");
        contactNoDt.setValue(conBasicInfo.getConNo());
        if (StringUtils.isNotBlank(conBasicInfo.getOrderNo())){
            DataTagWriter orderNoDt = doc.openDataTag("【订单编号】");
            orderNoDt.setValue(conBasicInfo.getOrderNo());
        }
        DataTagWriter totalDt = doc.openDataTag("【合同金额】");
        totalDt.setValue(conBasicInfo.getTotal().toString());
        DataTagWriter dtChineseTotal = doc.openDataTag("【合同金额-中文大写】");
        dtChineseTotal.setValue(AmountTransUtil.numberToUpperCaseRMB(conBasicInfo.getTotal()));
        fmCtrl.setWriter(doc);
        fmCtrl.fillDocumentAs(openFileUrl, DocumentOpenType.Word, conBasicInfo.getName());
        response.getOutputStream().print(fmCtrl.getHtml());
    }

    @PostMapping(value = "/updateDraftFile")
    @Operation(summary = "保存起草中文件")
    @Parameter(name = "id", description = "合同ID", required = true)
    @Parameter(name = "revisionCount", description = "Word中的修订痕迹数量", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void updateDraftFile(@NotNull(message = "合同ID不能为空") @RequestParam("id") Long id, Integer revisionCount
            , HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        revisionCount = revisionCount == null ? 0 : revisionCount;
        myConDraftService.updateWord(id, fs.getFileBytes(), revisionCount);
        fs.setCustomSaveResult("ok");
        fs.close();
    }

    @PutMapping("/update")
    @Operation(summary = "修改合同基本信息")
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult update(@Valid @RequestBody ConUpdateReq updateReq) {
        myConDraftService.updateById(updateReq);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除合同")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:delete')")
    public AjaxResult delete(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        myConDraftService.deleteById(id);
        return AjaxResult.success();
    }

    @PostMapping("/changeConFile")
    @Operation(summary = "更换合同文件")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult changeConFile(@NotNull(message = "合同ID不能为空") Long id
            ,@Parameter(name = "conFile", description = "合同文件", required = true) @NotNull(message = "合同文件不能为空") MultipartFile conFile) {
        myConDraftService.changeConFile(id, conFile);
        return AjaxResult.success();
    }

    @PutMapping("/changeConTemplate")
    @Operation(summary = "更换合同模板")
    @Parameter(name = "id", description = "合同ID", required = true)
    @Parameter(name = "templateId", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult changeConTemplate(@NotNull(message = "合同ID不能为空") Long id,@NotNull(message = "合同模板ID不能为空") Long templateId) {
        myConDraftService.changeConTemplate(id, templateId);
        return AjaxResult.success();
    }

    @PutMapping("/draftComplete/{id}")
    @Operation(summary = "起草完毕进入审核")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult draftComplete(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        myConDraftService.draftComplete(id);
        return AjaxResult.success();
    }

    @GetMapping(value = "/fileTemplate/page")
    @Operation(summary = "选择合同模板分页列表")
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<PageResult<ConFileTemplate>> page(@Valid @ParameterObject ConFileTemplateForSelectPageReq queryReq) {
        PageResult<ConFileTemplate> conFileTemplatePage = conFileTemplateService.getConFileTemplatePageForSelect(queryReq);
        return AjaxResult.success(conFileTemplatePage);
    }
}
